#!/bin/bash
# systemd-tmpfiles doesn't support skipping writing to files that already exist
# - copy the docker group to /etc because docker reads /etc/group directly
# - copy the sudo and wheel groups to /etc so that new uses can be added to them
# - copy the core and root users to /etc so the passwd utility works correctly

# Inherit root from environment or command line
ROOT="${1:-$ROOT}"
BASE="${ROOT}/usr/share/baselayout"

# Users/Groups to copy so they can be modified
COPY_USERS="root|core"
COPY_GROUPS="docker|sudo|wheel"

# readable files
umask 022
if [[ ! -e "${ROOT}/etc/passwd" ]]; then
    grep -E -e "^(${COPY_USERS}):" "${BASE}/passwd" > "${ROOT}/etc/passwd"
fi
if [[ ! -e "${ROOT}/etc/group" ]]; then
    grep -E -e "^(${COPY_GROUPS}):" "${BASE}/group" > "${ROOT}/etc/group"
fi

# secure files
umask 027
if [[ ! -e "${ROOT}/etc/shadow" ]]; then
    grep -E -e "^(${COPY_USERS}):" "${BASE}/shadow" > "${ROOT}/etc/shadow"
fi
if [[ ! -e "${ROOT}/etc/gshadow" ]]; then
    grep -E -e "^(${COPY_GROUPS}):" "${BASE}/gshadow" > "${ROOT}/etc/gshadow"
fi
